<template>
  <div class="schedule-calendar">
    <!-- 月份切换栏 -->
    <div class="month-nav">
      <el-button 
        type="text" 
        @click="prevMonth" 
        :disabled="isLoading"
        icon="el-icon-arrow-left"
      >
        上个月
      </el-button>
      <span class="current-date">
        {{ currentYear }}年 {{ currentMonth }}月
        <el-loading 
          v-if="isLoading" 
          size="small" 
          class="loading-icon"
        ></el-loading>
      </span>
      <el-button 
        type="text" 
        @click="nextMonth" 
        :disabled="isLoading"
        icon="el-icon-arrow-right"
      >
        下个月
      </el-button>
    </div>

    <!-- 日历表格：突出显示班休状态 -->
    <table class="calendar-table">
      <thead>
        <tr>
          <th>一</th>
          <th>二</th>
          <th>三</th>
          <th>四</th>
          <th>五</th>
          <th class="weekend">六</th>
          <th class="weekend">日</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(week, weekIndex) in calendarWeeks" :key="weekIndex">
          <td
            v-for="(day, dayIndex) in week"
            :key="dayIndex"
            :class="[
              { 'empty-day': !day },          // 空日期占位
              { 'holiday': day?.status === '休' }, // 休息日背景色
              { 'workday': day?.status === '班' }, // 工作日背景色
              { 'current-day': day?.isCurrentDay },// 当天高亮
              { 'weekend': dayIndex === 5 || dayIndex === 6 } // 周末列标记
            ]"
          >
            <div class="day-info" v-if="day">
              <!-- 公历日期 + 当天标记 -->
              <div class="solar-day">
                {{ day.solarDay }}
                <span class="current-dot" v-if="day.isCurrentDay"></span>
              </div>
              
              <!-- 农历日期 -->
              <div class="lunar-day" :class="{ 'non-current-month': !day.isCurrentMonth }">
                {{ day.lunarDay }}
              </div>
              
              <!-- 班休状态标签（重点优化显示） -->
              <div class="status-tag" :class="day.status === '休' ? 'status-rest' : 'status-work'">
                {{ day.status }}
              </div>
              
              <!-- 节日信息 -->
              <div class="festival" v-if="day.festival">
                {{ day.festival }}
              </div>
            </div>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { ElButton, ElLoading, ElMessage } from 'element-plus';
import 'element-plus/dist/index.css';

// 状态管理
const today = new Date();
const currentYear = ref(today.getFullYear());
const currentMonth = ref(today.getMonth() + 1);
const isLoading = ref(false);
const calendarDays = ref([]);

// 日历数据处理类
class CalendarService {
  constructor() {
    // 农历日名称映射
    this.lunarDays = ['初一', '初二', '初三', '初四', '初五', '初六', '初七', '初八', '初九', '初十',
                     '十一', '十二', '十三', '十四', '十五', '十六', '十七', '十八', '十九', '二十',
                     '廿一', '廿二', '廿三', '廿四', '廿五', '廿六', '廿七', '廿八', '廿九', '三十'];
                     
    // 节日数据
    this.solarFestivals = {
      '01-01': '元旦', '03-08': '妇女节', '03-12': '植树节', 
      '05-01': '劳动节', '06-01': '儿童节', '07-01': '建党节', 
      '08-01': '建军节', '09-10': '教师节', '10-01': '国庆节'
    };
    
    this.lunarFestivals = {
      '01-01': '春节', '01-15': '元宵节', '05-05': '端午节', 
      '07-07': '七夕节', '08-15': '中秋节', '09-09': '重阳节'
    };
    
    this.solarTerms = {
      '02-04': '立春', '02-19': '雨水', '03-06': '惊蛰', '03-21': '春分',
      '04-05': '清明', '04-20': '谷雨', '05-06': '立夏', '05-21': '小满',
      '06-06': '芒种', '06-21': '夏至', '07-07': '小暑', '07-23': '大暑',
      '08-07': '立秋', '08-23': '处暑', '09-08': '白露', '09-23': '秋分',
      '10-08': '寒露', '10-24': '霜降', '11-08': '立冬', '11-23': '小雪',
      '12-07': '大雪', '12-22': '冬至', '01-06': '小寒', '01-20': '大寒'
    };
    
    // 班休状态数据（2025年）
    this.holidays = {
      '01': ['01', '02', '03'], '02': ['08', '09', '10', '11', '12', '13', '14'],
      '04': ['05', '06', '07'], '05': ['01', '02', '03', '04', '05'], 
      '06': ['08', '09', '10'], '09': ['15', '16', '17'], 
      '10': ['01', '02', '03', '04', '05', '06', '07']
    };
    
    this.workdays = {
      '01': ['05', '06'], '02': ['02', '03'], '04': ['04'], 
      '05': ['08', '09'], '06': ['07'], '09': ['14', '28'], '10': ['11']
    };
  }

  // 获取指定月份的日历数据
  getMonthData(year, month, callback) {
    setTimeout(() => {
      try {
        if (!year || !month || month < 1 || month > 12) {
          throw new Error('无效的年月参数');
        }

        // 生成当月数据
        const monthData = this.generateMonthData(year, month);
        const formattedDays = monthData.days.map(day => this.formatDayData(day, year, month));
        
        // 补充上月和下月的占位日期
        const firstDayOfWeek = new Date(year, month - 1, 1).getDay() || 7;
        const prevDays = this.getPrevMonthDays(year, month, firstDayOfWeek - 1);
        const nextDays = this.getNextMonthDays(year, month, 42 - (prevDays.length + formattedDays.length));
        
        callback({ code: 200, data: [...prevDays, ...formattedDays, ...nextDays] });
      } catch (error) {
        callback({ code: 500, message: error.message });
      }
    }, 300);
  }

  // 格式化日期数据
  formatDayData(day, currentYear, currentMonth) {
    const isCurrentDay = day.year === today.getFullYear() && 
                         day.month === today.getMonth() + 1 && 
                         day.day === today.getDate();
                         
    return {
      solarDay: day.day,
      lunarDay: this.lunarDays[day.lunarDay - 1],
      festival: day.festivals.join('、'),
      status: day.workStatus,
      isCurrentMonth: day.month === currentMonth,
      isCurrentDay,
      date: day.date
    };
  }

  // 生成上月占位日期
  getPrevMonthDays(year, month, count) {
    if (count <= 0) return [];
    const prevMonth = month === 1 ? 12 : month - 1;
    const prevYear = month === 1 ? year - 1 : year;
    const totalDays = new Date(prevYear, prevMonth, 0).getDate();
    
    return Array.from({ length: count }, (_, i) => {
      const day = totalDays - count + 1 + i;
      const date = new Date(prevYear, prevMonth - 1, day);
      return {
        solarDay: day,
        lunarDay: this.lunarDays[this.getLunarDay(prevYear, prevMonth, day) - 1],
        festival: '',
        status: this.getWorkStatus(prevYear, prevMonth, day, date.getDay()),
        isCurrentMonth: false,
        isCurrentDay: false
      };
    });
  }

  // 生成下月占位日期
  getNextMonthDays(year, month, count) {
    if (count <= 0) return [];
    const nextMonth = month === 12 ? 1 : month + 1;
    const nextYear = month === 12 ? year + 1 : year;
    
    return Array.from({ length: count }, (_, i) => {
      const day = i + 1;
      const date = new Date(nextYear, nextMonth - 1, day);
      return {
        solarDay: day,
        lunarDay: this.lunarDays[this.getLunarDay(nextYear, nextMonth, day) - 1],
        festival: '',
        status: this.getWorkStatus(nextYear, nextMonth, day, date.getDay()),
        isCurrentMonth: false,
        isCurrentDay: false
      };
    });
  }

  // 生成当月完整数据
  generateMonthData(year, month) {
    const daysInMonth = new Date(year, month, 0).getDate();
    const days = [];
    for (let day = 1; day <= daysInMonth; day++) {
      days.push(this.generateDayData(year, month, day));
    }
    return { year, month, days };
  }

  // 生成单日详细数据
  generateDayData(year, month, day) {
    const date = new Date(year, month - 1, day);
    const weekDay = date.getDay();
    const lunarMonth = this.getLunarMonth(year, month);
    const lunarDay = this.getLunarDay(year, month, day);
    
    return {
      date: `${year}-${this.padZero(month)}-${this.padZero(day)}`,
      year,
      month,
      day,
      weekDay,
      lunarMonth,
      lunarDay,
      workStatus: this.getWorkStatus(year, month, day, weekDay),
      festivals: this.getFestivals(year, month, day, lunarMonth, lunarDay)
    };
  }

  // 获取班休状态（重点优化逻辑）
  getWorkStatus(year, month, day, weekDay) {
    const monthStr = this.padZero(month);
    const dayStr = this.padZero(day);
    
    // 优先判断调休上班
    if (year === 2025 && this.workdays[monthStr]?.includes(dayStr)) {
      return '班';
    }
    
    // 其次判断法定假日
    if (year === 2025 && this.holidays[monthStr]?.includes(dayStr)) {
      return '休';
    }
    
    // 最后判断周末
    if (weekDay === 0 || weekDay === 6) {
      return '休';
    }
    
    // 其余为工作日
    return '班';
  }

  // 获取节日信息
  getFestivals(year, month, day, lunarMonth, lunarDay) {
    const festivals = [];
    const solarKey = `${this.padZero(month)}-${this.padZero(day)}`;
    const lunarKey = `${this.padZero(lunarMonth)}-${this.padZero(lunarDay)}`;
    
    if (this.solarFestivals[solarKey]) festivals.push(this.solarFestivals[solarKey]);
    if (this.lunarFestivals[lunarKey]) festivals.push(this.lunarFestivals[lunarKey]);
    if (this.solarTerms[solarKey]) festivals.push(this.solarTerms[solarKey]);
    
    return festivals;
  }

  // 辅助方法：获取农历日
  getLunarDay(solarYear, solarMonth, solarDay) {
    // 简化的农历映射，实际应用中可接入专业农历库
    const lunarMap = {
      '2025-08-01': 14, '2025-08-02': 15, '2025-08-03': 16, '2025-08-04': 17,
      '2025-08-05': 18, '2025-08-06': 19, '2025-08-07': 20, '2025-08-08': 21,
      '2025-08-09': 22, '2025-08-10': 23, '2025-08-11': 24, '2025-08-12': 25,
      '2025-08-13': 26, '2025-08-14': 27, '2025-08-15': 28, '2025-08-16': 29,
      '2025-08-17': 30, '2025-08-18': 1,  '2025-08-19': 2,  '2025-08-20': 3,
      '2025-08-21': 4,  '2025-08-22': 5,  '2025-08-23': 6,  '2025-08-24': 7,
      '2025-08-25': 8,  '2025-08-26': 9,  '2025-08-27': 10, '2025-08-28': 11,
      '2025-08-29': 12, '2025-08-30': 13, '2025-08-31': 14
    };
    
    const key = `${solarYear}-${this.padZero(solarMonth)}-${this.padZero(solarDay)}`;
    return lunarMap[key] || Math.floor(Math.random() * 30) + 1;
  }

  // 辅助方法：获取农历月
  getLunarMonth(solarYear, solarMonth) {
    const lunarMonths = {
      2025: {1: 12, 2: 1, 3: 2, 4: 3, 5: 4, 6: 5, 7: 6, 8: 7, 9: 8, 10: 9, 11: 10, 12: 11}
    };
    return lunarMonths[solarYear]?.[solarMonth] || Math.floor(Math.random() * 12) + 1;
  }

  // 辅助方法：数字补零
  padZero(num) {
    return num < 10 ? `0${num}` : `${num}`;
  }
}

// 初始化服务
const calendarService = new CalendarService();

// 加载日历数据
const loadCalendarData = (year, month) => {
  isLoading.value = true;
  calendarService.getMonthData(year, month, (response) => {
    if (response.code === 200) {
      calendarDays.value = response.data;
    } else {
      ElMessage.error(`获取日历失败：${response.message}`);
    }
    isLoading.value = false;
  });
};

// 月份切换
const prevMonth = () => {
  if (currentMonth.value === 1) {
    currentMonth.value = 12;
    currentYear.value--;
  } else {
    currentMonth.value--;
  }
  loadCalendarData(currentYear.value, currentMonth.value);
};

const nextMonth = () => {
  if (currentMonth.value === 12) {
    currentMonth.value = 1;
    currentYear.value++;
  } else {
    currentMonth.value++;
  }
  loadCalendarData(currentYear.value, currentMonth.value);
};

// 按周分组
const calendarWeeks = computed(() => {
  const weeks = [];
  for (let i = 0; i < calendarDays.value.length; i += 7) {
    weeks.push(calendarDays.value.slice(i, i + 7));
  }
  return weeks;
});

// 页面挂载时加载数据
onMounted(() => {
  loadCalendarData(currentYear.value, currentMonth.value);
});
</script>

<style scoped>
.schedule-calendar {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: "Microsoft Yahei", "Helvetica Neue", Arial, sans-serif;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

/* 月份导航样式 */
.month-nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 10px;
}

.current-date {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  display: flex;
  align-items: center;
}

.loading-icon {
  margin-left: 10px;
}

/* 日历表格样式 */
.calendar-table {
  width: 100%;
  border-collapse: collapse;
  table-layout: fixed;
}

.calendar-table th,
.calendar-table td {
  border: 1px solid #e5e7eb;
  padding: 10px 5px;
  text-align: center;
  height: 100px;
  vertical-align: top;
}

.calendar-table th {
  background-color: #f8fafc;
  font-weight: 500;
  color: #666;
  height: 40px;
}

/* 日期单元格样式 */
.day-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 100%;
}

/* 公历日期 */
.solar-day {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 5px;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  border-radius: 50%;
}

/* 当天标记 */
.current-day .solar-day {
  background-color: #409eff;
  color: white;
}

.current-dot {
  display: none;
}

/* 农历日期 */
.lunar-day {
  font-size: 12px;
  color: #666;
  margin-bottom: 5px;
}

/* 非当月日期样式 */
.non-current-month .lunar-day,
.non-current-month .solar-day {
  color: #c0c4cc;
}

/* 班休状态标签（重点优化） */
.status-tag {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  margin-bottom: 5px;
  width: 36px;
  box-sizing: border-box;
}

/* 休息日状态样式 */
.status-rest {
  background-color: #e6f7ee;
  color: #00b42a;
  border: 1px solid #b7eb8f;
}

/* 工作日状态样式 */
.status-work {
  background-color: #e6f4ff;
  color: #1890ff;
  border: 1px solid #91d5ff;
}

/* 节日样式 */
.festival {
  font-size: 12px;
  color: #00b42a;
  line-height: 1.3;
  word-break: break-all;
  margin-top: auto;
  padding-bottom: 5px;
}

/* 周末样式 */
.weekend {
  color: #f56c6c;
}

/* 空日期样式 */
.empty-day {
  background-color: #fafafa;
}

/* 休息日和工作日背景色区分 */
.holiday {
  background-color: #f6ffed;
}

.workday {
  background-color: #fff;
}

/* 悬停效果 */
.calendar-table td:hover {
  background-color: #f0f9ff;
  transition: background-color 0.2s ease;
}
</style>
